import random
from datetime import datetime
from django.shortcuts import redirect, render, HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from app01 import models
from app01.utils.Bootstrap import BootStrapModelForm
from app01.utils.pagination import Pagination


class OrderModelForm(BootStrapModelForm):
    class Meta:
        model = models.Order
        # fields = "__all__"
        # 排除oid
        exclude = ['oid', 'admin']


def order_list(request):
    queryset = models.Order.objects.all().order_by('-id')
    page_object = Pagination(request, queryset)
    form = OrderModelForm()
    context = {
        "form": form,
        "page_queryset": page_object.page_queryset,
        "page_string": page_object.html()
    }
    return render(request, "order_list.html", context)


@csrf_exempt
def order_add(request):
    """新建订单（Ajax）请求"""
    # print(request.POST)
    # < QueryDict: {'title': ['开发部'], 'price': ['112'], 'status': ['1'], 'admin': ['2']} >
    form = OrderModelForm(data=request.POST)
    if form.is_valid():
        # 保存到数据库中
        # print(form.cleaned_data)
        # {'title': '开发部', 'price': Decimal('122.2'), 'status': 2, 'admin': < Admin: 李白 >}
        # 缺少oid
        # 额外增加一些不是用户输入的值（自己计算出来的）
        form.instance.oid = datetime.now().strftime("%Y%m%d%H%M%S") + str(random.randint(1000, 9999))
        # 设置管理员id，当前登录用户的id，去session中获取
        form.instance.admin_id = request.session["info"]["id"]
        form.save()
        return JsonResponse({"status": True})
    return JsonResponse({"status": False, 'error': form.errors})


def order_delete(request):
    """删除订单"""
    print(request.GET.get("uid"))
    uid = request.GET.get("uid")
    exists = models.Order.objects.filter(id=uid).exists()
    if not exists:
        return JsonResponse({"status": False, 'error': "删除失败，数据不存在"})
    models.Order.objects.filter(id=uid).delete()
    return JsonResponse({"status": True})


def order_detail(request):
    """根据订单id获取订单详细"""
    # uid = request.GET.get("uid")
    # row_object = models.Order.objects.filter(id=uid).first()
    # if not row_object:
    #     return JsonResponse({"status": False, 'error': "删除失败，数据不存在"})
    # # 从数据库中获取到一个对象
    # result = {
    #     "title": row_object.title,
    #     "price": row_object.price,
    #     "status": row_object.status
    # }
    # return JsonResponse({"status": True, "data": result})
    uid = request.GET.get("uid")
    # 用values选择属性,将得到一个字典类型
    row_dict = models.Order.objects.filter(id=uid).values("title", "price", "status").first()
    # 用values_list选择属性,将得到一个元组类型
    # row_tuple = models.Order.objects.filter(id=uid).values_list("title", "price", "status").first()
    if not row_dict:
        return JsonResponse({"status": False, 'error': "删除失败，数据不存在"})
    # 从数据库中获取到一个对象
    result = {
        "status": True,
        "data": row_dict
    }
    return JsonResponse(result)

@csrf_exempt
def order_edit(request):
    """编辑订单"""
    uid = request.GET.get("uid")
    row_object = models.Order.objects.filter(id=uid).first()
    if not row_object:
        return JsonResponse({"status":False, 'tips':"数据不存在，请刷新重试"})
    form = OrderModelForm(data=request.POST,instance=row_object)
    if form.is_valid():
        form.save()
        return JsonResponse({"status":True})
    return JsonResponse({"status": False, 'error': form.errors})


